<template>
  <div class="add_production_box">
    <el-dialog
      close-on-press-escape
      :title="isedit ? '编辑' + title : '添加' + title"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible="showDialog"
      width="750px"
      @close="handleClose(false)"
      @open="handleOpen"
    >
      <el-tabs
        v-model="activeName"
        :tab-position="tabPosition"
        class="tabHight"
      >
        <el-tab-pane name="first" label="详情">
          <el-form
            ref="productionForm"
            class="tab_form"
            label-position="right"
            :model="productionForm"
            :rules="productionFormRules"
            size="mini"
            label-width="auto"
          >
            <el-row :gutter="16" type="flex">
              <el-col :span="12">
                <el-form-item label="零件号:" prop="partNumber">
                  <el-select
                    ref="partRef"
                    v-model="productionForm.partNumber"
                    style="width: 100%"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                    @change="technologChange"
                  >
                    <el-option
                      v-for="item in technologyListUniqBy"
                      :key="item.token"
                      :label="item.partNumber"
                      :value="item.partNumber"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="零件名称:" prop="partName">
                  <el-input
                    v-model="productionForm.partName"
                    disabled
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托工序号:" prop="entrustProcessNumber">
                  <el-select
                    ref="processRef"
                    v-model="productionForm.entrustProcessNumber"
                    style="width: 100%"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                    @change="stepListChange"
                  >
                    <el-option
                      v-for="item in entrustProcessNumberListUniqBy"
                      :key="item.token"
                      :label="item.entrustProcessNumber"
                      :value="item.entrustProcessNumber"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托工序名称:" prop="entrustProcessName">
                  <el-input
                    v-model="productionForm.entrustProcessName"
                    disabled
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序/工步号:" prop="processNumber">
                  <el-select
                    ref="processRef"
                    v-model="productionForm.processNumber"
                    style="width: 100%"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                    @change="processListChange"
                  >
                    <el-option
                      v-for="item in processListUniqBy"
                      :key="item.token"
                      :label="item.processNumber"
                      :value="item.processNumber"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序/工步名称:" prop="processName">
                  <el-input
                    v-model="productionForm.processName"
                    disabled
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工艺版次:" prop="version">
                  <el-select
                    ref="processRef"
                    v-model="productionForm.version"
                    style="width: 100%"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                    @change="versionChange"
                  >
                    <el-option
                      v-for="item in versionListUniqBy"
                      :key="item.token"
                      :label="item.version"
                      :value="item.version"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工序版次:" prop="processVersion">
                  <el-select
                    ref="processRef"
                    v-model="productionForm.processVersion"
                    style="width: 100%"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                    @change="processVersionChange"
                  >
                    <el-option
                      v-for="item in processVersionListUniqBy"
                      :key="item.token"
                      :label="item.processVersion"
                      :value="item.processVersion"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="批次号:" prop="batchNumber">
                  <el-input
                    v-model="productionForm.batchNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="制造单元:" prop="manufactureSite">
                  <el-input
                    v-model="productionForm.manufactureSite"
                    disabled
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="版次:" prop="version">
                  <el-select
                    ref="processRef"
                    style="width: 100%"
                    v-model="productionForm.version"
                    filterable
                    placeholder="请选择"
                    size="mini"
                    value-key="token"
                  >
                    <el-option
                      v-for="item in versionList"
                      :key="item.version"
                      :label="item.version"
                      :value="item.version"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="材料牌号:" prop="materialMark">
                  <el-input
                    v-model="productionForm.materialMark"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来件数量:" prop="partTotalCount">
                  <el-input
                    v-model="productionForm.partTotalCount"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来件单位:" prop="unit">
                  <el-input
                    v-model="productionForm.unit"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="型别:" prop="model">
                  <el-input
                    v-model="productionForm.model"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品类别:" prop="productCategory">
                  <el-input
                    v-model="productionForm.productCategory"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发出部门编号:" prop="sendDepartmentNumber">
                  <el-input
                    v-model="productionForm.sendDepartmentNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发出部门:" prop="sendDepartmentName">
                  <el-input
                    v-model="productionForm.sendDepartmentName"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主制批次号:" prop="masterBatchNumber">
                  <el-input
                    v-model="productionForm.masterBatchNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主制顺序号:" prop="masterOrderNumber">
                  <el-input
                    v-model="productionForm.masterOrderNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="接收部门编码:"
                  prop="receiveDepartmentNumber"
                >
                  <el-input
                    v-model="productionForm.receiveDepartmentNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="接收部门:" prop="receiveDepartmentName">
                  <el-input
                    v-model="productionForm.receiveDepartmentName"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <!-- <el-tab-pane name="four" label="元数据" prop="metadata">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
            ref="metaDataRef"
          />
        </el-tab-pane> -->
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-if="isedit"
          size="mini"
          type="primary"
          :loading="btnLoading"
          @click="submitForm('productionForm')"
        >
          确 定</el-button
        >
        <el-button
          v-else
          :key="isedit"
          :loading="btnLoading"
          size="mini"
          type="primary"
          @click="submitForm('productionForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import MetaData from "@/views/opensite/metaData.vue";
import { getFormulass } from "@/api/technology";
import { postAccount, putAccount, getDetails } from "@/api/productionAccount";
import { VERSION_RULES } from "@/utils/local";
import { useAccountToken } from "@/utils/index";
export default {
  components: {
    // MetaData,
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    isedit: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    token: {
      type: String,
      default: ""
    },
    manufactureSite: {
      type: String,
      default: ""
    },
    reportId: {
      type: String,
      default: ""
    },
    templateId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      processVersionList: [],
      btnLoading: false,
      activeName: "first",
      tabPosition: "left",
      productionForm: {
        processVersion: "",
        entrustProcessNumber: "",
        entrustProcessName: "",
        materialGradle: "",
        version: "",
        cardNumber: "",
        batchNumber: "",
        specificationNumber: "",
        partName: "",
        partNumber: "",
        processNumber: "",
        processName: "",
        partTotalNumber: "",
        passTotalNumber: "",
        metadata: {},
        unit: "",
        model: "",
        productCategory: "",
        sendDepartmentNumber: "",
        sendDepartmentName: "",
        masterBatchNumber: "",
        masterOrderNumber: "",
        receiveDepartmentName: "",
        stepInfoList: [],
        receiveDepartmentNumber: "",
        partTotalCount: "",
        state: "就绪",
        manufactureSite: "",
        materialMark: ""
      },
      productionFormRules: {
        materialMark: [
          {
            required: true,
            message: "请输入材料牌号",
            trigger: ["blur", "change"]
          }
        ],
        manufactureSite: [
          { required: true, message: "请选择制造单元", trigger: "blur" }
        ],
        // unit: [{ required: true, message: "请输入来件单位", trigger: "blur" }],
        // cardNumber: [
        //   { required: true, message: "请输入上卡号", trigger: "blur" },
        // ],
        // version: VERSION_RULES,
        version: [
          { required: true, message: "请选择工艺版次", trigger: "change" }
        ],
        processVersion: [
          { required: true, message: "请输入工序版次", trigger: "change" }
        ],
        // specificationNumber: [
        //   { required: true, message: "请输入工艺规程编号", trigger: "blur" },
        // ],
        // partName: [
        //   { required: true, message: "请输入零件号", trigger: "blur" },
        // ],
        entrustProcessNumber: [
          { required: true, message: "请选择委托工序号", trigger: "change" }
        ],
        partNumber: [
          { required: true, message: "请选择零件号", trigger: "change" }
        ],
        processNumber: [
          { required: true, message: "请输入工序号", trigger: "change" }
        ],
        batchNumber: [
          {
            required: true,
            message: "请输入批次号",
            trigger: ["blur", "change"]
          }
        ],
        partTotalCount: [
          {
            required: true,
            message: "请输入来件数量",
            trigger: ["blur", "change"]
          },
          {
            validator(rule, value, callback) {
              var reg = /^\d+$/;
              if (!value) {
                callback();
              } else {
                if (reg.test(value)) {
                  callback();
                } else {
                  callback(new Error("来件数量必须为数字"));
                }
              }
            }
          }
        ]
        // passTotalNumber: [
        //   { required: true, message: "请输入完成数量", trigger: "blur" },
        // ],
      },
      metaDataJson: {},
      editmetaData: [],
      technologyList: [],
      processList: [],
      versionList: [],
      entrustProcessNumberList: []
    };
  },
  computed: {
    technologyListUniqBy() {
      return _.uniqBy(this.technologyList, "partNumber");
    },
    processListUniqBy() {
      return _.uniqBy(this.processList, "processNumber");
    },
    entrustProcessNumberListUniqBy() {
      return _.uniqBy(this.entrustProcessNumberList, "entrustProcessNumber");
    },
    versionListUniqBy() {
      return _.uniqBy(this.versionList, "version");
    },
    processVersionListUniqBy() {
      return _.uniqBy(this.processVersionList, "processVersion");
    }
  },
  async mounted() {},
  methods: {
    async versionChange() {
      const obj = this.versionList.find(item => item.version == val);
      this.productionForm.state =
        obj.deviceInfoList.length && obj.deviceInfoList[0].deviceList.length
          ? "就绪"
          : "未就绪";
      this.processVersionList = await this.getTechnologyList(
        this.productionForm.partNumber,
        this.productionForm.entrustProcessNumber,
        this.productionForm.processNumber,
        this.productionForm.version
      );
      this.productionForm.formulaId = this.processVersionList[0].id;
      this.productionForm.processVersion = this.processVersionList[0].processVersion;
    },
    processVersionChange(val) {
      const obj = this.processVersionList.find(
        item => item.processVersion == val
      );
      this.productionForm.state =
        obj.deviceInfoList.length && obj.deviceInfoList[0].deviceList.length
          ? "就绪"
          : "未就绪";
      this.productionForm.formulaId = obj.id;
    },
    async processListChange(val) {
      this.versionList = [];
      this.productionForm.version = "";
      this.processVersionList = [];
      this.productionForm.processVersion = "";
      const obj = this.technologyList.find(item => item.processNumber == val);
      console.log("obj :>> ", obj);
      this.productionForm.processName = obj.processName;
      this.productionForm.materialMark = obj.materialMark;
      this.productionForm.formulaId = obj.id;
      this.productionForm.state =
        obj.deviceInfoList.length && obj.deviceInfoList[0].deviceList.length
          ? "就绪"
          : "未就绪";
      // const technologyParameter = this.processList.find(
      //   item => item.processNumber == val
      // ).technology.technologyParameter;
      // this.productionForm.processName =
      //   technologyParameter.find(item => item.key == "工序名称")?.value || "";
      this.versionList = await this.getTechnologyList(
        this.productionForm.partNumber,
        this.productionForm.entrustProcessNumber,
        this.productionForm.processNumber
      );
      this.processVersionList = this.versionList;
      this.productionForm.version = this.versionList.length
        ? this.versionList[0].version
        : "";
      this.productionForm.processVersion = this.versionList[0].processVersion;
    },
    // 获取零件号 工序 版本
    getTechnologyList(
      partNumber,
      entrustProcessNumber,
      processNumber,
      version
    ) {
      return new Promise((resolve, reject) => {
        var params = {
          page: 1,
          pageSize: 0,
          partNumber,
          processNumber,
          entrustProcessNumber,
          version,
          state: true,
          includeTechnology: true,
          templateId: this.templateId
        };
        getFormulass(params).then(res => {
          const { results } = res.data;
          resolve(results);
        });
      });
    },
    async stepListChange(val) {
      this.processVersionList = [];
      this.versionList = [];
      this.productionForm.version = "";
      this.productionForm.processVersion = "";
      this.productionForm.processName = "";
      this.productionForm.processNumber = "";
      this.productionForm.materialMark = "";
      this.productionForm.formulaId = "";
      const obj = this.technologyList.find(
        item => item.entrustProcessNumber == val
      );
      this.productionForm.entrustProcessName = obj.entrustProcessName;
      console.log("obj :>> ", obj);
      this.processList = [];
      this.processList = await this.getTechnologyList(
        this.productionForm.partNumber,
        this.productionForm.entrustProcessNumber
      );
    },
    // 选择零件
    async technologChange(val) {
      this.processVersionList = [];
      this.versionList = [];
      this.productionForm.version = "";
      this.productionForm.processVersion = "";
      this.productionForm.processName = "";
      this.productionForm.processNumber = "";
      this.productionForm.entrustProcessNumber = "";
      this.productionForm.entrustProcessName = "";
      this.productionForm.formulaId = "";
      this.productionForm.materialMark = "";
      this.processList = [];
      this.entrustProcessNumberList = [];
      const obj = this.technologyList.find(item => item.partNumber == val);
      console.log("obj :>> ", obj);
      this.productionForm.partName = obj.partName;
      // const technologyParameter = this.technologyList.find(
      //   (item) => item.partNumber == val
      // ).technology.technologyParameter;
      // this.productionForm.partName =
      //   technologyParameter.find((item) => item.key == "零件名称")?.value || "";
      this.entrustProcessNumberList = await this.getTechnologyList(val);
      // this.$refs.processRef.focus();
    },

    // //获取设备类型列表
    // getDeviceTypeList() {
    //   var params = {
    //     page: 1,
    //     pageSize: 0,
    //   };

    // },
    // //获取设备列表
    // getDeviceList() {
    //   this.loading = true;
    //   var params = {
    //     includeDeviceType: false,
    //     includeAssignment: false,
    //     excludeAssigned: false,
    //     page: 1,
    //     pageSize: 0,
    //     deviceTypeList: this.deviceType,
    //   };
    // },
    getEditData() {
      getDetails(this.token).then(async res => {
        const r = res.data;
        this.productionForm = r;
        // this.productionForm.version = r.metadata.version;
        // this.processList = await this.getTechnologyList(r.partNumber);
        // this.versionList = await this.getTechnologyList(
        //   r.partNumber,
        //   r.processNumber
        // );
        this.entrustProcessNumberList = await this.getTechnologyList(
          r.partNumber
        );
        this.processList = await this.getTechnologyList(
          r.partNumber,
          r.entrustProcessNumber
        );
        this.versionList = await this.getTechnologyList(
          r.partNumber,
          r.entrustProcessNumber,
          r.processNumber
        );
        this.processVersionList = await this.getTechnologyList(
          r.partNumber,
          r.entrustProcessNumber,
          r.processNumber,
          r.version
        );
        // this.editmetaData = this.productionForm.metadata;
        // this.editmetaData = this.productionForm.metadata;
      });
    },
    // 弹窗打开执行操作
    async handleOpen() {
      this.technologyList = await this.getTechnologyList();
      this.$nextTick(() => {
        this.$refs.productionForm.resetFields();
        this.$refs.productionForm.clearValidate();
        this.$set(this.productionForm, "manufactureSite", this.manufactureSite);
        if (this.isedit) {
          this.getEditData();
        }
      });
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      this.$emit("closeDialog", isRefresh);
      this.cancelEmpty();
    },
    // 取消清空数据
    cancelEmpty() {
      this.processList = [];
      this.productionForm = {
        processVersion: "",
        entrustProcessNumber: "",
        entrustProcessName: "",
        materialGradle: "",
        version: "",
        cardNumber: "",
        batchNumber: "",
        specificationNumber: "",
        partName: "",
        partNumber: "",
        processNumber: "",
        processName: "",
        partTotalNumber: "",
        passTotalNumber: "",
        metadata: {},
        unit: "",
        model: "",
        productCategory: "",
        sendDepartmentNumber: "",
        sendDepartmentName: "",
        masterBatchNumber: "",
        masterOrderNumber: "",
        receiveDepartmentName: "",
        stepInfoList: [],
        receiveDepartmentNumber: "",
        partTotalCount: "",
        state: "就绪",
        manufactureSite: "",
        materialMark: ""
      };
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true;
          let formData = {};
          formData = Object.assign({}, this.productionForm);
          formData.metadata = this.metaDataJson;
          formData.reportId = this.reportId;
          // formData.manufactureSite = this.manufactureSite;
          console.log("formData", formData);
          // formData.metadata.version = this.productionForm.version;
          this.btnLoading = true;
          if (this.isedit) {
            putAccount(formData, this.token)
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                this.handleClose(true);
              })
              .finally(f => {
                this.btnLoading = false;
              });
          } else {
            formData.token = "";
            postAccount(formData)
              .then(res => {
                this.$msg({
                  type: "success",
                  message: "操作成功!"
                });
                this.handleClose(true);
              })
              .finally(f => {
                this.btnLoading = false;
              });
          }
          this.loading = false;
        } else {
          this.$msg("数据校验失败,请检查!");
          return false;
        }
      });
    },
    // 元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    }
  }
};
</script>

<style lang="scss" scoped>
.tab_form {
  /* margin-right: 15px; */
  /deep/ .el-row--flex {
    flex-wrap: wrap;
  }
}
</style>
